//
//  NetworkTools.swift
//  YYWeiBo
//
//  Created by 崔洋洋 on 15/10/10.
//  Copyright © 2015年 崔洋洋. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {

    // 单例
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
       let tools = NetworkTools(baseURL: baseURL)
        
        // 设置数据解析数据类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
    }()
    
    // MARK: - OAuth 授权
    private let clientId = "3662679181"
    private let appSecret = "9958197f14be408f1fc58a3aea2a65b1"
    
    // 回调地址
    let redirectUri = "http://www.hao123.com"
    
    // 返回 OAuth 授权地址
    func oauthUrl() ->NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    // 加载 Token
    func loadAccessToken(code: String, finished: (result:[String: AnyObject]?, error: NSError?)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri,
        ]
        
        // MARK - 测试代码
//        responseSerializer = AFHTTPResponseSerializer()
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
//            print(NSString(data: JSON as! NSData, encoding: NSUTF8StringEncoding))
            
            finished(result: JSON as? [String: AnyObject], error: nil)
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
}
